package org.pvt.model;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.HashSet;
import java.util.Set;

import static org.pvt.model.db.DBUtils.getReadableDB;

/**
 * @author Pavel Talanov
 */
public abstract class HasNameAndBelongsToEvent extends HasName {

    /*package*/
    static HasNameAndBelongsToEvent createModel(@NotNull final String tableName) {
        return new HasNameAndBelongsToEvent() {
            @NotNull
            @Override
            public String getTableName() {
                return tableName;
            }
        };
    }

    /*package*/ HasNameAndBelongsToEvent() {
    }

    @NotNull
    @Override
    protected Set<Field> getFields() {
        Set<Field> fields = new HashSet<Field>(super.getFields());
        fields.add(new Field(Models.Event, Behaviour.CASCADE));
        return fields;
    }


    @NotNull
    public Cursor getCursor(long eventId, @NotNull Context context) {
        SQLiteDatabase readableDatabase = getReadableDB(context);
        Cursor query = readableDatabase.query(getTableName(), getFieldNames(), referenceById(Models.Event) + " = " + eventId, new String[]{}, null, null, null);
        // readableDatabase.close();
        return query;
    }

    @Nullable
    public String getNameById(long id, @NotNull Context context) {
        SQLiteDatabase readableDatabase = getReadableDB(context);
        Cursor query = readableDatabase.query(getTableName(), new String[]{NAME}, ID + " = ?",
                new String[]{String.valueOf(id)}, null, null, null);
        String result;
        if (query.moveToFirst()) {
//            Log.d("debug", String.valueOf(query.getColumnIndex(ID)));
//            int columnIndex = query.getColumnIndex(NAME);
//            Log.d("debug", "Column index is " + String.valueOf(columnIndex));
            result = query.getString(0);
        } else {
            result = null;

        }
        query.close();
        return result;
    }
}
